

function resetFieldsetForm() {
    $('#legend-text').val('');
}

$(function() {

    // validation rules
    var rules = {};
    rules['legend']                         = set_rules('legend', 'legend', 'required|maxlength[255]');
    rules['location']                       = set_rules('location', 'location', 'required|maxlength[25]');

    // fieldset form validation
    $("#fieldset-form").validate({
        errorElement: 'small',
        errorClass: 'help-block',
        rules: rules,
        errorPlacement:function(error, element) {
            element.parents('.input-size').append( '<div class="clear-fix"></div>' );
            element.parents('.input-size').append( error);
        },
        highlight: function(label) {
            $(label).closest('.form-group').removeClass('has-error has-success').addClass('has-error');
        },
        success: function(label) {
            label.addClass('valid').closest('.form-group').removeClass('has-error has-success').addClass('has-success');
        }
    });

    $('#generic-fieldset-btn').click(function() {
        resetFieldsetForm();
        $('#fieldset-modal').modal({
            width: '55%'
        });
    });
    
    $('#fieldset-save-btn').click(function(event) {
        event.preventDefault();
        
        $('#fieldset-form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });
        
        if( $('#fieldset-form').valid()) {

            var values = $('#fieldset-form').serializeJSON();
            
            // label
            var legendPosition = values['location'] !== undefined ? ' ' + values['location'] : '';
            var legendText = values['legend'] !== undefined ? values['legend'] : '';
            
            // HTML markup for fieldset legend
            var markup = '';
            markup += '<li>';
            markup += '<fieldset>';
            markup += '<legend class="handle' + legendPosition + '">' +legendText+ '</legend>';
            markup += '<ul class="sortable sortable-connected">';
            markup += '&nbsp;';
            markup += '</ul>';
            markup += '</fieldset>';
            markup += '</li>';

            $('#form-sortable').prepend(markup);

            $( ".sortable" ).sortable({
                cursor: 'move',
                dropOnEmpty: true,
                placeholder: 'sortable-placeholder',
                connectWith: '.sortable-connected'
            });
            
            $('#fieldset-modal').modal('hide');

        }
        
        // submit form for validation purposes
        $('#fieldset-form').submit();

    });
    
});

